package com.fingard.dsp.bank.directbank.cgbunion01.util;


import org.apache.commons.io.IOUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class HttpClientUtils {
    private final static Logger log = LoggerFactory.getLogger(HttpClientUtils.class);
	//设置链接超时和请求超时等参数，否则会长期停止或者崩溃
    private static RequestConfig REQUEST_CONFIG = RequestConfig.custom()
            .setSocketTimeout(60000)
            .setConnectTimeout(60000)
            .setConnectionRequestTimeout(60000)
            .build();
    
    public static HttpResult sendHttpPostWithCustomHeader(String url, String data, Map<String, String> headerMap) throws Exception {
        CloseableHttpClient client = null;
        HttpResult result = new HttpResult();
        try {
            client = HttpClients.custom()
                    .setDefaultRequestConfig(REQUEST_CONFIG).build();
            HttpPost httpPost = new HttpPost(url);
            StringEntity entity = new StringEntity(data, "utf-8");
            httpPost.setEntity(entity);
            if(headerMap != null && headerMap.size() > 0) {
                Iterator<String> it = headerMap.keySet().iterator();
                while(it.hasNext()) {
                    String key = it.next();
                    httpPost.setHeader(key, headerMap.get(key));
                }
            }
            CloseableHttpResponse response = client.execute(httpPost);
            log.info("response ---> {}", response);
            if(response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            	throw new RuntimeException(response.getStatusLine().toString());
            }
            Header[] headers = response.getAllHeaders();
            if(headers != null && headers.length > 0) {
                Map<String, String> temHeaderMap = new HashMap<String, String>();
                for(Header head : headers) {
                    temHeaderMap.put(head.getName(),head.getValue());
                }
                result.setHeaderMap(temHeaderMap);
            }
            HttpEntity entityResult = response.getEntity();
            result.setResult(EntityUtils.toString(entityResult));
            return result;
        } catch (Exception e) {
        	throw e;
        } finally {
        	IOUtils.closeQuietly(client);
        }
    }
}
